//
//  SMAFNetworkItem.m
//  NetwrokDemo
//
//  Created by Ted Liu on 16/5/4.
//  Copyright © 2016年 Ted Liu. All rights reserved.
//

#import "SMAFNetworkItem.h"
#import "SMAFNetworkSessionManager.h"
#import "SMAFNetworkDefine.h"
#import "DSToast.h"

@interface SMAFNetworkItem ()

@end

@implementation SMAFNetworkItem


#pragma mark - 创建一个网络请求项，开始请求网络
/**
 *  创建一个网络请求项，开始请求网络
 *
 *  @param networkType  网络请求方式
 *  @param url          网络请求URL
 *  @param params       网络请求参数
 *  @param delegate     网络请求的委托，如果没有取消网络请求的需求，可传nil
 *  @param hashValue    网络请求的委托delegate的唯一标示
 *  @param showHUD      是否显示HUD
 *  @param successBlock 请求成功后的block
 *  @param failureBlock 请求失败后的block
 *
 *  @return SMAFNetworkItem对象
 */
- (SMAFNetworkItem *)initWithtype:(SMAFNetWorkType)networkType
                               url:(NSString *)url
                            params:(NSDictionary *)params
                        serverType:(SMNetServer) server
                          delegate:(id)delegate
                         hashValue:(NSUInteger)hashValue
                           showHUD:(BOOL)showHUD
                      successBlock:(SMAFSuccessBlock)successBlock
                      failureBlock:(SMAFFailureBlock)failureBlock
{
    if (self = [super init])
    {
        self.networkType    = networkType;
        self.url            = url;
        self.params         = params;
        self.delegate       = delegate;
        self.showHUD        = showHUD;
        if (showHUD==YES) {
            [MBProgressHUD showActiveMessageNew:@"正在加载数据..." withBackground:YES];
        }
        __weak typeof(self)weakSelf = self;
        AFHTTPSessionManager *manager = nil;
        switch (server) {
            case SMNetServer_Default: {
                manager = [SMAFNetworkSessionManager sharedInstance].sessionManager_def;
                break;
            }
            case SMNetServer_Call: {
                manager = [SMAFNetworkSessionManager sharedInstance].sessionManager_Call;
                break;
            }
            case SMNetServer_Wallet: {
                manager = [SMAFNetworkSessionManager sharedInstance].sessionManager_Wallet;
                break;
            }
            case SMNetServer_Adv: {
                manager = [SMAFNetworkSessionManager sharedInstance].sessionManager_adv;
                break;
            }
            case SMNetServer_Base: {
                manager = [SMAFNetworkSessionManager sharedInstance].sessionManager_base;
                break;
            }
            case SMNetServer_Static: {
                manager = [SMAFNetworkSessionManager sharedInstance].sessionManager_Static;
                break;
            }
        }
        
        if (networkType==SMAFNetWorkGET)
        {
            [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [weakSelf requestSuccessTreated:task response:responseObject successBlock:successBlock];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [weakSelf requestFailTreated:task response:error failureBlock:failureBlock];
            }];
            
        }
        else if (networkType == SMAFNetWorkPOST){
            [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [weakSelf requestSuccessTreated:task response:responseObject successBlock:successBlock];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [weakSelf requestFailTreated:task response:error failureBlock:failureBlock];
            }];
        }
        else if (networkType == SMAFNetWorkPATCH){
            
            [manager PATCH:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [weakSelf requestSuccessTreated:task response:responseObject successBlock:successBlock];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [weakSelf requestFailTreated:task response:error failureBlock:failureBlock];
            }];
        }
    }
    return self;
}

/**
 *  请求成功处理
 */
- (void) requestSuccessTreated:(NSURLSessionDataTask * _Nonnull) task response:(id  _Nullable) responseObject successBlock:(SMAFSuccessBlock)successBlock{
    
    [MBProgressHUD dismissHUD];
    __weak typeof(self)weakSelf = self;
    SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
    response.resultDic = responseObject;
    response.resultCode = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
    
    // 暂时修改以后可能会变
    if (!response.resultCode || [response.resultCode isEqualToString:@"(null)"]||[response.resultCode isKindOfClass:[NSNull class]]) {
        response.resultCode = @"200";
    }
    
    ITTDPRINT(@"\n\n----请求的返回结果 %@\n",responseObject);
    if (successBlock) {
        successBlock(task,response);
    }
    if ([weakSelf.delegate respondsToSelector:@selector(requestDidFinishLoading:)]) {
        [weakSelf.delegate requestDidFinishLoading:responseObject];
    }
    [weakSelf removewItem];
}

/**
 *  请求失败处理
 */
- (void) requestFailTreated:(NSURLSessionDataTask * _Nonnull) task response:(NSError * _Nonnull) error failureBlock:(SMAFFailureBlock)failureBlock{
    
    __weak typeof(self)weakSelf = self;
    [MBProgressHUD dismissHUD];
    SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
    if (error.userInfo[@"NSLocalizedDescription"] == NULL)
    {
        response.errorMessage = @"";
    } else{
        response.errorMessage = error.userInfo[@"NSLocalizedDescription"];
    }
    [MBProgressHUD showWithTitle:@"网络请求失败请重试!"];
    ITTDPRINT(@"---error==%@\n",error.localizedDescription);
    // 失败block
    if (failureBlock) {
        failureBlock(task,response,error);
    }
    // 失败代理
    if ([weakSelf.delegate respondsToSelector:@selector(requestdidFailWithError:)]) {
        [weakSelf.delegate requestdidFailWithError:error];
    }
    [weakSelf removewItem];
}


/**
 *   移除网络请求项
 */
- (void)removewItem
{
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([weakSelf.delegate respondsToSelector:@selector(netWorkWillDealloc:)]) {
            [weakSelf.delegate netWorkWillDealloc:weakSelf];
        }
    });
}
@end
